package service

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"io/ioutil"
	"newRetailByGolang/genericity"
	"newRetailByGolang/model"
	"newRetailByGolang/utils"
	"newRetailByGolang/variable"
	"os"
	"sync"
	"time"
)

type OrderService struct {
	Order        *model.Order
	OrderChan    chan *model.Order
	OrderChanMap map[string]chan *model.Order
	lock         sync.Mutex
	lockOther    sync.Mutex
}

func NewOrderService() *OrderService {
	os := OrderService{
		Order:        model.NewOrder(),
		OrderChan:    make(chan *model.Order, 5),
		OrderChanMap: make(map[string]chan *model.Order),
		lock:         sync.Mutex{},
		lockOther:    sync.Mutex{},
	}
	return &os
}

func (orderService *OrderService) InsertOrder(o *model.Order) (map[string]interface{}, error) {

	defer func() {
		if err := recover(); err != nil {
			// 打印异常，关闭资源，退出此函数
			fmt.Println(err)
		}
	}()

	orderService.OrderChan <- o

	//orderService.OrderChanMap[o.UserName] = orderService.OrderChan

	go func() {
		takeOrder := <-orderService.OrderChan
		fmt.Println("takeOrder：", *takeOrder)
		takeOrder.CreatedAt = time.Now()
		takeOrder.UpdatedAt = time.Now()
		orderService.Order.InsertOrder(takeOrder)

		variable.Db.Model(&takeOrder).Update("user_name", "更新木有。。。。")

		variable.Db.Delete(&model.Order{}, 11)
	}()

	go func() {
		uw := new(utils.Worker)

		var guc = &genericity.GenericUnified[model.Order]{
			Pojo: model.Order{
				Id:        uw.GetId() + 222,
				UserId:    uw.GetId(),
				UserName:  "genericity 新增 UserName",
				GoodId:    uw.GetId(),
				GoodName:  "genericity 新增 GoodName",
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			},
		}
		guc.Created()

		var gud = &genericity.GenericUnified[model.Order]{Pojo: model.Order{}}
		gud.Delete(100)

		var guu = &genericity.GenericUnified[model.Order]{
			Pojo: model.Order{
				Id:        50,
				UserId:    uw.GetId(),
				UserName:  "genericity 修改 UserName",
				GoodId:    uw.GetId(),
				GoodName:  "genericity 修改 GoodName",
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			},
		}
		guu.Update()

		var guq = &genericity.GenericUnified[model.Order]{Pojo: model.Order{}}
		os := guq.QueryAll(map[string]interface{}{})
		fmt.Println("os：", os)

	}()

	go func() {
		uw := new(utils.Worker)

		co := model.Order{
			Id:        uw.GetId() + 333,
			UserId:    uw.GetId(),
			UserName:  "genericity function 新增 UserName",
			GoodId:    uw.GetId(),
			GoodName:  "genericity function 新增 GoodName",
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		genericity.Created(co)

		do := model.Order{}
		genericity.Delete(do, 39)

		uo := model.Order{
			Id:        81,
			UserId:    uw.GetId(),
			UserName:  "genericity function 修改 GoodName",
			GoodId:    uw.GetId(),
			GoodName:  "genericity function 修改 GoodName",
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		genericity.Update(uo)

		qo := model.Order{}
		qo = genericity.Query(qo, 29)
		fmt.Println("qo：", qo)

		qao := []model.Order{}
		qao = genericity.QueryAll(qao, map[string]interface{}{})
		fmt.Println("qao：", qao)

		o := model.Order{
			Id:       541002723800223321,
			UserId:   uw.GetId(),
			UserName: "genericity 多对多 修改 UserName",
			GoodId:   uw.GetId(),
			GoodName: "genericity 多对多 修改 GoodName",
			GoodIdList: []int64{
				758254652436000000,
				423658132547000000,
				675906590891000000,
			},
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		//genericity.ManyCreated[model.Order, model.OrderGood](o, model.OrderGood{}, "GoodIdList", "OrderId", "GoodId")

		//genericity.ManyDelete(o, model.OrderGood{}, "order_id")

		genericity.ManyUpdate[model.Order, model.OrderGood](o, model.OrderGood{}, "GoodIdList", "OrderId", "GoodId")

		m := genericity.GenerityMapTest[string, model.Order](map[string][]*model.Order{
			"genericity_map1": []*model.Order{
				&model.Order{
					Id:        uw.GetId(),
					UserId:    uw.GetId(),
					UserName:  "泛型map UserName1",
					GoodId:    uw.GetId(),
					GoodName:  "泛型map GoodName1",
					CreatedAt: time.Now(),
					UpdatedAt: time.Now(),
				},
				&model.Order{
					Id:        uw.GetId(),
					UserId:    uw.GetId(),
					UserName:  "泛型map UserName2",
					GoodId:    uw.GetId(),
					GoodName:  "泛型map GoodName2",
					CreatedAt: time.Now(),
					UpdatedAt: time.Now(),
				},
				&model.Order{
					Id:        uw.GetId(),
					UserId:    uw.GetId(),
					UserName:  "泛型map UserName3",
					GoodId:    uw.GetId(),
					GoodName:  "泛型map GoodName3",
					CreatedAt: time.Now(),
					UpdatedAt: time.Now(),
				},
			},
			"genericity_map2": []*model.Order{
				&model.Order{
					Id:        uw.GetId(),
					UserId:    uw.GetId(),
					UserName:  "泛型map UserName4",
					GoodId:    uw.GetId(),
					GoodName:  "泛型map GoodName4",
					CreatedAt: time.Now(),
					UpdatedAt: time.Now(),
				},
				&model.Order{
					Id:        uw.GetId(),
					UserId:    uw.GetId(),
					UserName:  "泛型map UserName5",
					GoodId:    uw.GetId(),
					GoodName:  "泛型map GoodName5",
					CreatedAt: time.Now(),
					UpdatedAt: time.Now(),
				},
				&model.Order{
					Id:        uw.GetId(),
					UserId:    uw.GetId(),
					UserName:  "泛型map UserName6",
					GoodId:    uw.GetId(),
					GoodName:  "泛型map GoodName6",
					CreatedAt: time.Now(),
					UpdatedAt: time.Now(),
				},
			},
		})
		fmt.Println("m：", m)
	}()

	return map[string]interface{}{"code": 200, "message": "成功", "data": nil}, nil
}

func (orderService *OrderService) InsertOrderInPool(o *model.Order) (map[string]interface{}, error) {

	defer func() {
		if err := recover(); err != nil {
			// 打印异常，关闭资源，退出此函数
			fmt.Println("pool error：", err)
		}
	}()

	variable.Sp.Add(func() error {
		//fmt.Println(o.GoodId)
		//fmt.Println(o.GoodName)
		//fmt.Println("-------------------------------------------------------------------------------")

		o.CreatedAt = time.Now()
		o.UpdatedAt = time.Now()
		orderService.Order.InsertOrder(o)

		variable.Db.Model(&o).Update("user_name", "pool 更新木有。。。。")

		variable.Db.Delete(&model.Order{}, 14)

		return nil
	})

	return map[string]interface{}{"code": 200, "message": "成功", "data": nil}, nil
}

func (orderService *OrderService) InsertOrderInRedisQueue(o *model.Order) (map[string]interface{}, error) {

	defer func() {
		if err := recover(); err != nil {
			// 打印异常，关闭资源，退出此函数
			fmt.Println("redis queue err：", err)
		}
	}()

	ob, _ := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(o)
	_, err := (*variable.R).Do("rpush", variable.RMQ, ob)
	if err != nil {
		fmt.Println("produce error")
		return nil, err
	}

	return map[string]interface{}{"code": 200, "message": "成功", "data": nil}, nil
}

func (orderService *OrderService) GetFileInfo(folder string) *model.FileInfo {
	fileInfo, err := os.Stat(folder)
	if os.IsNotExist(err) {
		fmt.Println("file not exist")
	}

	return &model.FileInfo{
		Name:        fileInfo.Name(),
		IsDir:       fileInfo.IsDir(),
		ModTime:     fileInfo.ModTime(),
		Size:        fileInfo.Size(),
		SubFileInfo: []*model.FileInfo{},
	}
}

func (orderService *OrderService) NewGetFiles(folder string) interface{} {
	defer func() {
		err := recover()
		if err != nil {
			return
		}
	}()

	s, _ := os.Stat(folder)
	if !s.IsDir() {
		f, _ := os.ReadFile(folder)
		return string(f)
	}

	var file_list []*model.FileInfo
	files, _ := ioutil.ReadDir(folder)
	for _, file := range files {
		fi := orderService.GetFileInfo(folder + "/" + file.Name())
		file_list = append(file_list, fi)
	}

	return file_list
}
